package com.bnyy.medicalHousekeeper.moudle.message.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.NotificationUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;
import com.bnyy.medicalHousekeeper.moudle.message.ChatManager;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.moudle.message.activity.ChatContactsActvitiy;
import com.bnyy.medicalHousekeeper.moudle.message.activity.ChatMessageActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.NoticeAlarmsActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.NoticeGoodsActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.NoticeLocationAuthoritiesActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.SearchContactActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.StrangerChatsActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.VerificationMessageActivity;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ChatAdapter;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.IndexChatAdapter;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactGroup;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.message.bean.Message;
import com.bnyy.message.bean.chat.Chat;
import com.bnyy.message.bean.chat.ChatMessage;
import com.bnyy.message.event.ChatMessageEvent;
import com.bnyy.message.event.ReceiveMessageEvent;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/8
 **/
public class ChatsFragment extends BaseFragmentImpl {
    @BindView(R.id.ll_search)
    RelativeLayout llSearch;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.iv_close_open_notice_tips)
    ImageView ivCloseOpenNoticeTips;
    @BindView(R.id.ll_open_notice)
    LinearLayout llOpenNotice;
    @BindView(R.id.tv_notice_tips)
    TextView tvNoticeTips;

    private IndexChatAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_index_chats;
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SpanUtils.with(tvNoticeTips)
                .append("打开通知，及时收到互动消息")
                .appendSpace(SizeUtils.dp2px(12))
                .append("开启 >").setBold().setForegroundColor(Color.BLUE)
                .create();

        ivCloseOpenNoticeTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llOpenNotice.setVisibility(View.GONE);
                ivCloseOpenNoticeTips.setTag(true);
            }
        });

        llOpenNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 26) {
                    // android 8.0引导
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("android.provider.extra.APP_PACKAGE", mContext.getPackageName());
                } else if (Build.VERSION.SDK_INT >= 21) {
                    // android 5.0-7.0
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("app_package", mContext.getPackageName());
                    intent.putExtra("app_uid", mContext.getApplicationInfo().uid);
                } else {
                    // 其他
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });

        ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent intent = result.getData();
                        if (intent != null) {
                            Contact contact = (Contact) intent.getSerializableExtra("contact");
                            if (contact != null) {
                                ChatMessageActivity.show(mContext, contact);
                            }
                        }
                    }
                });

        llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HashMap<String, ArrayList<? extends Contact>> datas = new HashMap<>();
                requestManager.request(requestManager.mMessageRetrofitService.getFriendList(),
                        new BaseObserverImpl<ArrayList<ContactUser>>() {
                            @Override
                            public void onSuccess(ArrayList<ContactUser> contactUsers) {
                                super.onSuccess(contactUsers);
                                if (contactUsers.size() > 0) {
                                    datas.put("我的好友", contactUsers);
                                }

                                requestManager.request(requestManager.mMessageRetrofitService.getGroupList(),
                                        new BaseObserverImpl<ArrayList<ContactGroup>>() {
                                            @Override
                                            public void onSuccess(ArrayList<ContactGroup> contactGroups) {
                                                super.onSuccess(contactGroups);
                                                if (contactGroups.size() > 0) {
                                                    datas.put("我的群组", contactGroups);
                                                }

                                                SearchContactActivity.show(mContext, datas, launcher);
                                            }
                                        });
                            }
                        });
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setItemAnimator(null);
        adapter = new IndexChatAdapter(mContext, new ChatAdapter.Callback() {
            @Override
            public void onItemClick(Chat chat) {
                switch (chat.getChatType()) {
                    case GROUP_CHAT:
                    case PRIVATE_CHAT:
                        ChatMessageActivity.show(mContext, chat);
                        break;
                    case VERIFICATION:
                        VerificationMessageActivity.show(mContext, chat);
                        break;
                    case STRANGER:
                        BaseActivityImpl.show(mContext, StrangerChatsActivity.class);
                        break;
                    case NOTICE_NEW_FANS:
                        MessageManager.clearUnreadCount(chat);
                        BaseActivityImpl.show(mContext, ChatContactsActvitiy.class);
                        break;
                    case NOTICE_ALARM:
                        MessageManager.clearUnreadCount(chat);
                        BaseActivityImpl.show(mContext, NoticeAlarmsActivity.class);
                        break;
                    case NOTICE_LOCATION_AUTHORITY:
                        MessageManager.clearUnreadCount(chat);
                        BaseActivityImpl.show(mContext, NoticeLocationAuthoritiesActivity.class);
                        break;
                    case NOTICE_GOODS:
                        MessageManager.clearUnreadCount(chat);
                        BaseActivityImpl.show(mContext, NoticeGoodsActivity.class);
                        break;
                }
            }

            @Override
            public void topping(Chat chat) {
//                adapter.onDataChange(chat);
                refresh();
            }

            @Override
            public void delete(Chat chat) {
                refresh();
            }

            @Override
            public void noDisturb(Chat chat) {

            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void refresh() {
        if (NotificationUtils.areNotificationsEnabled()) {
            llOpenNotice.setVisibility(View.GONE);
        } else {
            llOpenNotice.setVisibility(View.VISIBLE);
        }

        init();
    }

    private void init() {
        ArrayList<Chat> localChats = MessageManager.getChats();

        HashSet<String> localChatIds = new HashSet<>();

        localChats.forEach(new Consumer<Chat>() {
            @Override
            public void accept(Chat chat) {
                chat.setChatInfo(MessageManager.getChatInfo(chat.getChatId()));
                localChatIds.add(chat.getChatId());
            }
        });
        requestManager.request(requestManager.mMessageRetrofitService.getGroupList(),
                new BaseObserverImpl<ArrayList<ContactGroup>>() {
                    @Override
                    public void onSuccess(ArrayList<ContactGroup> contactGroups) {
                        super.onSuccess(contactGroups);
                        int loginUserId = userInfoManager.getLoginUserId();

                        for (ContactGroup contactGroup : contactGroups) {
                            Chat chat = new Chat(loginUserId, contactGroup.getId());
                            if (localChatIds.add(chat.getChatId()) && chat.getChatInfo() != null) {
                                localChats.add(chat);
                            }
                        }
                        init(localChats, localChatIds);
                    }
                });
    }

    private void init(ArrayList<Chat> totalChats, HashSet<String> localChatIds) {
        boolean enable = true;

        for (Chat chat : totalChats) {

            switch (chat.getChatType()) {
                case PRIVATE_CHAT:
                case GROUP_CHAT:
                case STRANGER:
                    if (chat.getContactUsers() == null) {
                        enable = false;
                    }
                    break;
            }
            if (!enable) {
                break;
            }
        }

        if (enable) {
            ArrayList<Chat> toppingChats = new ArrayList<>();
            ArrayList<Chat> indexChats = new ArrayList<>();

            totalChats.forEach(new Consumer<Chat>() {
                @Override
                public void accept(Chat chat) {
                    Log.e("indexChat", new Gson().toJson(chat));
                    switch (chat.getChatType()) {
                        case PRIVATE_CHAT:
                        case GROUP_CHAT:
                        case STRANGER:
                            if (chat.getChatInfo() != null && chat.getChatInfo().isTopping()) {
                                if (chat.getToppingTime() == 0) {
                                    if (chat.getRecipientRoleId() == 4) {
                                        chat.setToppingTime(-System.currentTimeMillis());
                                    } else {
                                        chat.setToppingTime(System.currentTimeMillis());
                                    }
                                }
                                toppingChats.add(chat);
                            } else {
                                indexChats.add(chat);
                            }
                            break;
                        default:
                            indexChats.add(chat);
                            break;
                    }

                }
            });
            indexChats.sort(new Comparator<Chat>() {
                @Override
                public int compare(Chat o1, Chat o2) {
                    if (o1.getTime() > o2.getTime()) {
                        return -1;
                    }
                    return 0;
                }
            });

            toppingChats.sort(new Comparator<Chat>() {
                @Override
                public int compare(Chat o1, Chat o2) {
                    if (o1.getToppingTime() < o2.getToppingTime()) {
                        return -1;
                    }
                    return 0;
                }
            });


            indexChats.addAll(0, toppingChats);

            adapter.refresh(indexChats);
        } else {
            LinkedList<Chat> chatLinkedList = new LinkedList<>(totalChats);
            ArrayList<Chat> target = new ArrayList<>();

            Consumer<Chat> consumer = new Consumer<Chat>() {
                @Override
                public void accept(Chat chat) {

                    if (!localChatIds.contains(chat.getChatId())) {
                        MessageManager.save(chat);
                    }

                    target.add(chat);
                    if (chatLinkedList.size() > 0) {
                        Chat poll = chatLinkedList.poll();

                        switch (poll.getChatType()) {
                            case PRIVATE_CHAT:
                            case GROUP_CHAT:
                            case STRANGER:
                                if (poll.getContactUsers() == null) {
                                    ChatManager.getChat(poll, this);
                                }
                                break;
                            default:
                                accept(poll);
                                break;
                        }
                    } else {
                        init(target, localChatIds);
                    }
                }
            };
            Chat poll = chatLinkedList.poll();

            switch (poll.getChatType()) {
                case PRIVATE_CHAT:
                case GROUP_CHAT:
                case STRANGER:
                    if (poll.getContactUsers() == null) {
                        ChatManager.getChat(poll, consumer);
                    }
                    break;
                default:
                    consumer.accept(poll);
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ReceiveMessageEvent event) {
        if (isResumed() && !isHidden()) {
            Message message = event.getMessage();
            if (message != null) {
                if (message instanceof ChatMessage) {
                    if (adapter != null) {
                        refresh();
//                        adapter.onDataChange(new Chat(userInfoManager.getLoginUserId(), (ChatMessage) message));
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChatMessageEvent event) {
        if (isResumed() && !isHidden()) {
            ChatMessageEvent.Type type = event.getType();
            switch (type) {
                case GET_OFF_LINE_CHAT:
                    refresh();
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refresh();
        }
    }
}





































